package com.example.wuyeguanli.activity;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.wuyeguanli.R;
import com.example.wuyeguanli.entiy.Facility;
import com.example.wuyeguanli.entiy.FacilityRental;
import com.example.wuyeguanli.entiy.Response;
import com.example.wuyeguanli.tools.ApiClient;
import com.example.wuyeguanli.tools.DataValidator;
import com.example.wuyeguanli.tools.FacilityAdapter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class FacilityBookingActivity extends AppCompatActivity {
    private final String TAG = "ApiClient";
    private Button btnBack, btnSubmit;
    private Spinner spinnerFacility;
    private EditText telephone, reasonText;
    private TextView timeText;
    private ProgressBar loadingProgress;
    private FacilityAdapter adapter;
    private final ApiClient apiClient = new ApiClient();
    private Calendar startCalendar = Calendar.getInstance();
    private Calendar endCalendar = Calendar.getInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_facilitybooking);
        if(getSupportActionBar() != null) getSupportActionBar().hide();

        initViews();
        setupSpinner();
        loadFacilities();
        setupInitialTime();
        setupListeners();
    }

    private void initViews() {
        btnBack = findViewById(R.id.btn_back);
        spinnerFacility = findViewById(R.id.spinner_faclity);
        telephone = findViewById(R.id.telephone);
        reasonText = findViewById(R.id.reason_text);
        timeText = findViewById(R.id.time_text);
        btnSubmit = findViewById(R.id.btn_submit);
        loadingProgress = findViewById(R.id.loading_progress);
    }

    private void setupSpinner() {
        adapter = new FacilityAdapter(this, new ArrayList<>());
        spinnerFacility.setAdapter(adapter);
    }

    private void loadFacilities() {
        setLoadingState(true, "正在加载设施列表...");
        apiClient.getFacilities(new ApiClient.OnCompleteListener<Response<List<Facility>>>() {
            @Override
            public void onSuccess(Response<List<Facility>> data) {
                setLoadingState(false, null);
                if (data != null && "success".equals(data.getState()) && data.getData() != null) {
                    adapter.clear();
                    adapter.addAll(data.getData());
                    adapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(FacilityBookingActivity.this, data != null ? data.getError() : "加载设施失败", Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void OnError(Throwable error) {
                setLoadingState(false, null);
                Log.e(TAG, "LoadFacilities OnError: ", error);
                Toast.makeText(FacilityBookingActivity.this, "网络错误，加载设施失败", Toast.LENGTH_LONG).show();
            }
        });
    }

    private void setupInitialTime() {
        endCalendar.add(Calendar.HOUR_OF_DAY, 1);
        updateDateTimeDisplay();
    }

    private void setupListeners() {
        btnBack.setOnClickListener(v -> finish());
        btnSubmit.setOnClickListener(v -> handleSubmitFlow());
        timeText.setOnClickListener(v -> showStartDateTimePicker());
    }

    private void showStartDateTimePicker() {
        new DatePickerDialog(this, (view, year, month, dayOfMonth) -> {
            startCalendar.set(year, month, dayOfMonth);
            showStartTimePicker();
        }, startCalendar.get(Calendar.YEAR), startCalendar.get(Calendar.MONTH), startCalendar.get(Calendar.DAY_OF_MONTH)).show();
    }
    private void showStartTimePicker() {
        new TimePickerDialog(this, (timeView, hourOfDay, minute) -> {
            startCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
            startCalendar.set(Calendar.MINUTE, minute);
            showEndDateTimePicker();
        }, startCalendar.get(Calendar.HOUR_OF_DAY), startCalendar.get(Calendar.MINUTE), true).show();
    }
    private void showEndDateTimePicker() {
        new DatePickerDialog(this, (view, year, month, dayOfMonth) -> {
            endCalendar.set(year, month, dayOfMonth);
            showEndTimePicker();
        }, endCalendar.get(Calendar.YEAR), endCalendar.get(Calendar.MONTH), endCalendar.get(Calendar.DAY_OF_MONTH)).show();
    }
    private void showEndTimePicker() {
        new TimePickerDialog(this, (timeView, hourOfDay, minute) -> {
            endCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
            endCalendar.set(Calendar.MINUTE, minute);
            updateDateTimeDisplay();
        }, endCalendar.get(Calendar.HOUR_OF_DAY), endCalendar.get(Calendar.MINUTE), true).show();
    }

    private void updateDateTimeDisplay() {
        SimpleDateFormat displayFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
        String displayText = displayFormat.format(startCalendar.getTime()) + "\n至\n" + displayFormat.format(endCalendar.getTime());
        timeText.setText(displayText);
    }

    private void handleSubmitFlow() {
        if (!validateInput()) return;
        setLoadingState(true, "正在获取工单号...");

        // 步骤1: 获取工单号
        apiClient.generateWorkOrder("facility", new ApiClient.OnCompleteListener<Response<String>>() {
            @Override
            public void onSuccess(Response<String> data) {
                if (data != null && "success".equals(data.getState())) {
                    setLoadingState(true, "正在提交预定...");
                    // 步骤2: 提交预定数据
                    submitBookingData(data.getData());
                } else {
                    setLoadingState(false, null);
                    Toast.makeText(FacilityBookingActivity.this, "获取工单号失败: " + (data != null ? data.getError() : "未知错误"), Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void OnError(Throwable error) {
                setLoadingState(false, null);
                Log.e(TAG, "GenerateWorkOrder OnError: ", error);
                Toast.makeText(FacilityBookingActivity.this, "网络错误，获取工单号失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private boolean validateInput() {
        if (spinnerFacility.getSelectedItem() == null) {
            Toast.makeText(this, "请先选择一个设施", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!DataValidator.isValidPhoneNumber(telephone.getText().toString())) {
            Toast.makeText(this, "电话号要求11位数字且第一位数字不为0", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!DataValidator.isNotEmpty(reasonText.getText().toString())) {
            Toast.makeText(this, "租借原因不得为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (startCalendar.after(endCalendar)) {
            Toast.makeText(this, "结束时间不能早于开始时间", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void submitBookingData(String workOrderId) {
        Facility selectedFacility = (Facility) spinnerFacility.getSelectedItem();
        SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
        String startTime = isoFormat.format(startCalendar.getTime());
        String endTime = isoFormat.format(endCalendar.getTime());

        FacilityRental facilityRental = new FacilityRental(
                workOrderId,
                selectedFacility.getFacilityId(),
                telephone.getText().toString(),
                reasonText.getText().toString(),
                startTime,
                endTime
        );

        apiClient.addFacilityRental(facilityRental, new ApiClient.OnCompleteListener<Response<Object>>() {
            @Override
            public void onSuccess(Response<Object> data) {
                setLoadingState(false, null);
                if (data.getState().equals("success")) {
                    Toast.makeText(FacilityBookingActivity.this, "设施预定成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(FacilityBookingActivity.this, data.getError(), Toast.LENGTH_LONG).show();
                }
            }
            @Override
            public void OnError(Throwable error) {
                setLoadingState(false, null);
                Log.e(TAG, "AddFacilityRental OnError: ", error);
                Toast.makeText(FacilityBookingActivity.this, "网络错误，提交失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setLoadingState(boolean isLoading, String message) {
        loadingProgress.setVisibility(isLoading ? View.VISIBLE : View.GONE);
        btnSubmit.setEnabled(!isLoading);
        spinnerFacility.setEnabled(!isLoading);
        telephone.setEnabled(!isLoading);
        reasonText.setEnabled(!isLoading);
        timeText.setEnabled(!isLoading);
        if (isLoading && message != null) {
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        }
    }
}